package com.ibangnuo.manage.service.commercial;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibangnuo.framework.domain.*;
import com.ibangnuo.framework.domain.ext.CommercialTenantExt;
import com.ibangnuo.framework.domain.ext.CommercialTenantNewExt;
import com.ibangnuo.framework.domain.request.commercial.CommercialTenantNewRequest;
import com.ibangnuo.framework.domain.request.commercial.CommercialTenantRequest;
import com.ibangnuo.framework.exception.ExceptionCast;
import com.ibangnuo.framework.model.response.*;
import com.ibangnuo.framework.utils.MD5Utils;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.UserRepository;
import com.ibangnuo.manage.dao.channel.ChannelMapper;
import com.ibangnuo.manage.dao.channel.ChannelRepository;
import com.ibangnuo.manage.dao.employee.CommercialMapper;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.EmployeeRepository;
import com.ibangnuo.manage.dao.newLandpay.CommercialTenantDetailsRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author: wwy
 * @Date: 2019-12-30 11:18
 */
@Transactional
@Service
public class CommercialService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private CommercialTenantDetailsRepository commercialTenantDetailsRepository;
    @Autowired
    private CommercialMapper commercialMapper;
    @Autowired
    private ChannelMapper channelMapper;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private EmployeeRepository employeeRepository;


    /**
     * 商户添加
     *
     * @param commercialTenantExt
     * @return
     */
    public ResponseResult add(CommercialTenantExt commercialTenantExt) {
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        User user = new User();
        user.setUsername(commercialTenantExt.getUsername());
        user.setPassword(MD5Utils.md5(commercialTenantExt.getPassword(), "wang"));
        user.setStatus(0);
        user.setStatus(0);
        user.setType(2);
        user.setIsDelete(1);
        user.setUserpic(commercialTenantExt.getPhoto());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        User userSave = userRepository.save(user);
        String commercialJson = JSONObject.toJSONString(commercialTenantExt);
        CommercialTenant commercialTenant = JSONObject.parseObject(commercialJson, CommercialTenant.class);
        commercialTenant.setUserId(userSave.getId());
        commercialTenant.setUsername(commercialTenantExt.getUsername());
        commercialTenant.setImageList("");
        commercialTenant.setIsDelete(1);
        if (user1.getType() == 0) {
            //管理员添加商户
            if (commercialTenantExt.getAgentIdAgentId() != null && commercialTenantExt.getAgentIdAgentId() != "") {
                commercialTenant.setAgentId(commercialTenantExt.getMerchantsIdAgentId());
            }
        } else {
            //代理商添加商户，查询代理商
            Agent agent = this.getAgentByUserId(user1.getId());
            commercialTenant.setAgentId(agent.getId());//代理商id
        }
        commercialTenant.setStatus(0);//冻结
        commercialTenant.setCreateTime(new Date());
        commercialTenant.setNumber(String.valueOf(PrimaryKeyUtil.nextId()));
        commercialRepository.save(commercialTenant);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 分页条件查询
     *
     * @param commercialTenantRequest
     * @return
     */
    public QueryResponseResult findList(CommercialTenantRequest commercialTenantRequest) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (commercialTenantRequest == null) {
            new CommercialTenantRequest();
        }
        String id = user.getId();
        CommercialTenant commercialTenant = new CommercialTenant();
        if (user.getType() == 0) {//管理员查询
            commercialTenant.setAgentId(commercialTenantRequest.getMerchantsIdAgentId());
        } else if (user.getType()==1){ //代理商查询
            Agent agentByUserId = this.getAgentByUserId(user.getId());
            commercialTenant.setAgentId(agentByUserId.getId());
        }else if (user.getType()==4){//员工
            String id1 = user.getId();
            Employee byUserId = employeeRepository.findByUserId(id1);
            commercialTenant.setEmployeeId(byUserId.getId());
        }


        if (StringUtils.isNotEmpty(commercialTenantRequest.getUsername())) {
            commercialTenant.setUsername(commercialTenantRequest.getUsername());
        }
        if (StringUtils.isNotEmpty(commercialTenantRequest.getName())) {
            commercialTenant.setName(commercialTenantRequest.getName());
        }
        if (StringUtils.isNotEmpty(commercialTenantRequest.getPhone())) {
            commercialTenant.setPhone(commercialTenantRequest.getPhone());
        }
        if (StringUtils.isNotEmpty(commercialTenantRequest.getEmail())) {
            commercialTenant.setEmail(commercialTenantRequest.getEmail());
        }
        if (commercialTenantRequest.getStatus() != null) {
            commercialTenant.setStatus(commercialTenantRequest.getStatus());
        }
        if (StringUtils.isNotEmpty(commercialTenantRequest.getNumber())) {
            commercialTenant.setNumber(commercialTenantRequest.getNumber());
        }

       /* if (StringUtils.isNotEmpty(agentByUserId.getCompanyName())) {
            commercialTenant.setCompanyName(agentByUserId.getCompanyName());
        }*/


        commercialTenant.setIsDelete(1);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("number", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("phone", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("email", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("status", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("isDelete", ExampleMatcher.GenericPropertyMatchers.exact());
        Example<? extends CommercialTenant> example = Example.of(commercialTenant, exampleMatcher);
        int page = commercialTenantRequest.getPage();
        int size = commercialTenantRequest.getLimit();
        if (page <= 0) {
            page = 1;
        }
        page = page - 1;
        if (size <= 0) {
            size = 10;
        }
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(page, size,sort);
        Page<? extends CommercialTenant> all = commercialRepository.findAll(example, pageable);
        QueryResult queryResult = new QueryResult();

        List<CommercialTenantExt> list = new ArrayList<>();
        for (CommercialTenant tenant : all) {//下面是获取该商户申请通道的状态
            String tenantId = tenant.getId();
            List<Channel> channel = channelRepository.findByCommercialId(tenantId);
            if (channel == null || channel.size() <= 0) {

                CommercialTenantExt commercialTenantExt = new CommercialTenantExt();
              /*  commercialTenantExt.setWxStatus("未申请");
                commercialTenantExt.setAliPayStatus("未申请");
                commercialTenantExt.setJlStatus("未申请");*/
                String a = JSONObject.toJSONString(tenant);
                Map A = JSONObject.parseObject(a, Map.class);

                String b = JSONObject.toJSONString(commercialTenantExt);
                Map B = JSONObject.parseObject(b, Map.class);
                B.putAll(A);
                String string = JSONObject.toJSONString(B);
                CommercialTenantExt commercialTenantExt1 = JSONObject.parseObject(string, CommercialTenantExt.class);
                list.add(commercialTenantExt1);
            }
            for (Channel channel1 : channel) {
                CommercialTenantExt commercialTenantExt = new CommercialTenantExt();
                int type = channel1.getType();
                int status = channel1.getStatus();
                if (type == 1) {
                    if (1 == type && 0 == status) {//微信
                        commercialTenantExt.setWxStatus("审核通过");
                    } else if (1 == type && 0 == status) {
                        commercialTenantExt.setWxStatus("审核未通过");
                    } else if (1 == type && 0 == status) {
                        commercialTenantExt.setWxStatus("未申请");
                    }
                }
                if (type == 2) {
                    if (2 == type && 0 == status) {//支付宝
                        commercialTenantExt.setAliPayStatus("审核通过");
                    } else if (2 == type && 1 == status) {
                        commercialTenantExt.setAliPayStatus("审核未通过");
                    } else if (2 == type && 2 == status) {
                        commercialTenantExt.setAliPayStatus("未申请");
                    }
                }
                if (type == 3) {
                    if (3 == type && 0 == status) {//建联
                        commercialTenantExt.setJlStatus("审核通过");
                    } else if (3 == type && 1 == status) {
                        commercialTenantExt.setJlStatus("审核未通过");
                    } else if (3 == type && 2 == status) {
                        commercialTenantExt.setJlStatus("未申请");
                    }
                }


                String a = JSONObject.toJSONString(tenant);
                Map A = JSONObject.parseObject(a, Map.class);

                String b = JSONObject.toJSONString(commercialTenantExt);
                Map B = JSONObject.parseObject(b, Map.class);
                B.putAll(A);
                String string = JSONObject.toJSONString(B);
                CommercialTenantExt commercialTenantExt1 = JSONObject.parseObject(string, CommercialTenantExt.class);
                list.add(commercialTenantExt1);
            }
        }
        queryResult.setTotal(all.getTotalElements());
        queryResult.setList(list);
//        queryResult.setList(all.getContent());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public ObjectResult findById(String id) {
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if (optional.isPresent()) {
            return new ObjectResult(CommonCode.SUCCESS, optional.get());
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public ObjectResult findByIdNew(String id) {
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if (!optional.isPresent()) {

        }
        CommercialTenant commercialTenant = optional.get();
        CommercialTenantDetails commercialTenantDetails = commercialTenantDetailsRepository.findByCommercialTenantId(commercialTenant.getId());
        if(commercialTenantDetails == null){
            commercialTenantDetails = new CommercialTenantDetails();
        }
        CommercialTenantNewExt commercialTenantNewExt = new CommercialTenantNewExt();
        commercialTenantNewExt.setCommercialTenant(commercialTenant);
        commercialTenantNewExt.setCommercialTenantDetails(commercialTenantDetails);
        return new ObjectResult(CommonCode.SUCCESS, commercialTenantNewExt);
    }

    /**
     * 根据id更新
     *
     * @param id
     * @param commercialTenantExt
     * @return
     */
    public ResponseResult update(String id, CommercialTenantExt commercialTenantExt) {
        CommercialTenant one = this.getCommercialTenantById(id);
        if (one != null) {
            one.setCompanyName(commercialTenantExt.getCompanyName());
            one.setPhone(commercialTenantExt.getPhone());
            one.setEmail(commercialTenantExt.getEmail());
            one.setAlipayNum(commercialTenantExt.getAlipayNum());
            one.setPosition(commercialTenantExt.getPosition());
            one.setProvince(commercialTenantExt.getProvince());
            one.setCity(commercialTenantExt.getCity());
            one.setArea(commercialTenantExt.getArea());
            one.setRemark(commercialTenantExt.getRemark());
            one.setStatus(commercialTenantExt.getStatus());
            User user = this.getUserById(one.getUserId());
            if (user == null) {
                ExceptionCast.cast(CommonCode.SERVER_ERROR);
            }
            if (StringUtils.isNotEmpty(commercialTenantExt.getPassword())) {
                user.setPassword(MD5Utils.md5(commercialTenantExt.getPassword(), "wang"));
            }
            user.setStatus(commercialTenantExt.getStatus());

            commercialRepository.save(one);
            userRepository.save(user);
            String channelStatus = commercialTenantExt.getChannelStatus();
            Optional<Channel> byId = channelRepository.findById(id);
            if (channelStatus.equals("1")) {//微信申请成功
                if (byId.isPresent()) {
                    Channel channel = byId.get();
                    channel.setStatus(0);
                    channel.setType(1);
                    channelRepository.save(channel);
                }
            } else if (channelStatus.equals("2")) {//支付宝申请成功
                if (byId.isPresent()) {
                    Channel channel = byId.get();
                    channel.setType(2);
                    channel.setStatus(0);
                    channelRepository.save(channel);
                }
            } else if (channelStatus.equals("3")) {//建联申请成功
                if (byId.isPresent()) {
                    Channel channel = byId.get();
                    channel.setType(3);
                    channel.setStatus(0);
                    channelRepository.save(channel);
                }
            }
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    /**
     * 根据id更新图片资源
     *
     * @param id
     * @param map
     * @return
     */
    public ResponseResult updateImage(String id, Map<String, Object> map) {
        CommercialTenant one = this.getCommercialTenantById(id);
        String jsonString = JSONObject.toJSONString(map);
        one.setImageList(jsonString);
        commercialRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据id更新删除状态
     *
     * @param id
     * @return
     */
    public ResponseResult delete(String id) {
        CommercialTenant one = this.getCommercialTenantById(id);
        User userOne = this.getUserById(one.getUserId());
        one.setIsDelete(0);
        userOne.setIsDelete(0);
        commercialRepository.save(one);
        userRepository.save(userOne);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 新版商户添加
     * 1.第一次添加，初始化建单
     * 判断是否是初始化，判断id是否存在值，未存在进行初始化
     * 2.其他添加，进行更新操作
     *
     * @return
     */
    public ObjectResult addNew(CommercialTenantNewExt commercialTenantNewExt) {
        if (commercialTenantNewExt == null) {
            return new ObjectResult(CommonCode.FAIL, null);
        }
        CommercialTenant commercialTenant = commercialTenantNewExt.getCommercialTenant();
        CommercialTenantDetails commercialTenantDetails = commercialTenantNewExt.getCommercialTenantDetails();
        if (StringUtils.isEmpty(commercialTenant.getId())) {
            //初始化建单
            User user1 = (User) SecurityUtils.getSubject().getPrincipal();
            //查询代理商
            Agent agent = this.getAgentByUserId(user1.getId());
            /*User user = new User();
            user.setStatus(0);
            user.setType(2);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            User userSave = userRepository.save(user);*/
            /*commercialTenant.setStatus(0);
            commercialTenant.setIsDelete(1);
            commercialTenant.setCreateTime(new Date());
            commercialTenant.setAgentId(agent.getId());
            commercialTenant.setUserId(userSave.getId());
            commercialTenant.setNumber(String.valueOf(PrimaryKeyUtil.nextId()));
            CommercialTenant save = commercialRepository.save(commercialTenant);
            commercialTenantDetails.setCommercialTenantId(save.getId());*/
            CommercialTenant save = commercialRepository.save(commercialTenant);
            commercialTenantDetails.setCommercialTenantId(save.getId());
            commercialTenantDetails.setCreateTime(new Date());
            commercialTenantDetails.setUpdateTime(new Date());
            commercialTenantDetails.setCustomsStatus(0);
            commercialTenantDetailsRepository.save(commercialTenantDetails);
            Map<String, Object> map = new HashMap<>();
            map.put("id", save.getId());
            return new ObjectResult(CommonCode.SUCCESS, map);
        }
        //更新操作
        CommercialTenantNewExt one = this.getCommercialTenantNewExt(commercialTenant.getId());
        if (one != null) {
            CommercialTenant commercialTenantOne = one.getCommercialTenant();
            CommercialTenantDetails commercialTenantDetailsOne = one.getCommercialTenantDetails();
            if(StringUtils.isEmpty(commercialTenantDetailsOne.getId())){
                commercialTenantDetails.setCommercialTenantId(commercialTenant.getId());
                commercialTenantDetails.setCreateTime(new Date());
                commercialTenantDetails.setUpdateTime(new Date());
                commercialTenantDetails.setCustomsStatus(0);
                commercialTenantDetailsOne = commercialTenantDetailsRepository.save(commercialTenantDetails);
            }
           /* commercialTenantOne.setName(commercialTenant.getName());
            commercialTenantOne.setUsername(commercialTenant.getUsername());
            commercialTenantOne.setCompanyName(commercialTenant.getCompanyName());*/
            commercialTenantOne.setArea(commercialTenant.getArea());
            commercialTenantOne.setCity(commercialTenant.getCity());
            commercialTenantOne.setProvince(commercialTenant.getProvince());
            commercialTenantOne.setStep(commercialTenant.getStep());
            commercialTenantOne.setRemark(commercialTenant.getRemark());
            commercialTenantOne.setPosition(commercialTenant.getPosition());
            commercialTenantOne.setAlipayNum(commercialTenant.getAlipayNum());
            commercialTenantOne.setEmail(commercialTenant.getEmail());
            commercialTenantOne.setPhone(commercialTenant.getPhone());
            commercialTenantOne.setAddressDetailed(commercialTenant.getAddressDetailed());
            commercialTenantOne.setType(commercialTenant.getType());


            commercialTenantDetailsOne.setFeeRat(commercialTenantDetails.getFeeRat());
            commercialTenantDetailsOne.setFeeRat1(commercialTenantDetails.getFeeRat1());
            commercialTenantDetailsOne.setFeeRat1Scan(commercialTenantDetails.getFeeRat1Scan());
            commercialTenantDetailsOne.setFeeRat2Scan(commercialTenantDetails.getFeeRat2Scan());
            commercialTenantDetailsOne.setFeeRat3Scan(commercialTenantDetails.getFeeRat3Scan());
            commercialTenantDetailsOne.setFeeRatScan(commercialTenantDetails.getFeeRatScan());
            commercialTenantDetailsOne.setMaxFeeAmt(commercialTenantDetails.getMaxFeeAmt());
            commercialTenantDetailsOne.setYsfcreditfee(commercialTenantDetails.getYsfcreditfee());
            commercialTenantDetailsOne.setYsfdebitfee(commercialTenantDetails.getYsfdebitfee());
            commercialTenantDetailsOne.setBusEffDt(commercialTenantDetails.getBusEffDt());
            commercialTenantDetailsOne.setCrpEffDt(commercialTenantDetails.getCrpEffDt());
            commercialTenantDetailsOne.setBusLicNo(commercialTenantDetails.getBusLicNo());
            commercialTenantDetailsOne.setStlOac(commercialTenantDetails.getStlOac());
            commercialTenantDetailsOne.setIncomType(commercialTenantDetails.getIncomType());
            commercialTenantDetailsOne.setBnkAcnm(commercialTenantDetails.getBnkAcnm());
            commercialTenantDetailsOne.setWcLbnkNo(commercialTenantDetails.getWcLbnkNo());
            commercialTenantDetailsOne.setBseLiceNm(commercialTenantDetails.getBseLiceNm());
            commercialTenantDetailsOne.setCrpNm(commercialTenantDetails.getCrpNm());
            commercialTenantDetailsOne.setMercAdds(commercialTenantDetails.getMercAdds());
            commercialTenantDetailsOne.setBusExpDt(commercialTenantDetails.getBusExpDt());
            commercialTenantDetailsOne.setCrpExpDt(commercialTenantDetails.getCrpExpDt());
            commercialTenantDetailsOne.setCrpIdNo(commercialTenantDetails.getCrpIdNo());
            commercialTenantDetailsOne.setStoeNm(commercialTenantDetails.getStoeNm());
            commercialTenantDetailsOne.setStoeCntNm(commercialTenantDetails.getStoeCntNm());
            commercialTenantDetailsOne.setStoeCntCardid(commercialTenantDetails.getStoeCntCardid());
            commercialTenantDetailsOne.setStoeCntTel(commercialTenantDetails.getStoeCntTel());
            commercialTenantDetailsOne.setStoeAdds(commercialTenantDetails.getStoeAdds());
            commercialTenantDetailsOne.setTrmRec(commercialTenantDetails.getTrmRec());
            commercialTenantDetailsOne.setTrmTp(commercialTenantDetails.getTrmTp());
            commercialTenantDetailsOne.setTrmScan(commercialTenantDetails.getTrmScan());
            commercialTenantDetailsOne.setMailbox(commercialTenantDetails.getMailbox());
            commercialTenantDetailsOne.setAlipayFlg(commercialTenantDetails.getAlipayFlg());
            commercialTenantDetailsOne.setYhkpayFlg(commercialTenantDetails.getYhkpayFlg());
            commercialTenantDetailsOne.setMerchantsType1(commercialTenantDetails.getMerchantsType1());
            commercialTenantDetailsOne.setMerchantsType2(commercialTenantDetails.getMerchantsType2());
            commercialTenantDetailsOne.setUpdateTime(commercialTenantDetails.getUpdateTime());
            commercialTenantDetailsOne.setIcrpIdNo(commercialTenantDetails.getIcrpIdNo());
            commercialTenantDetailsOne.setCrpEndDt(commercialTenantDetails.getCrpEndDt());
            commercialTenantDetailsOne.setCrpStartDt(commercialTenantDetails.getCrpStartDt());
            commercialTenantDetailsOne.setStoeAreaCod(commercialTenant.getArea());

            commercialTenantDetailsOne.setStlTyp(commercialTenantDetails.getStlTyp());
            commercialTenantDetailsOne.setStlSign(commercialTenantDetails.getStlSign());

            commercialTenantDetailsOne.setSettlementParty(commercialTenantDetails.getSettlementParty());

            commercialTenantDetailsOne.setCardTyp(commercialTenantDetails.getCardTyp());
            commercialTenantDetailsOne.setTranTyps(commercialTenantDetails.getTranTyps());
            commercialTenantDetailsOne.setSuptDbfreeFlg(commercialTenantDetails.getSuptDbfreeFlg());
            if (commercialTenant.getStep() == 4) {
                commercialTenantDetailsOne.setCustomsStatus(1);
            } else {
                commercialTenantDetailsOne.setCustomsStatus(0);
            }
            CommercialTenant save = commercialRepository.save(commercialTenantOne);

            commercialTenantDetailsRepository.save(commercialTenantDetailsOne);
            Map<String, Object> map = new HashMap<>();
            map.put("id", save.getId());
            return new ObjectResult(CommonCode.SUCCESS, map);
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 查询全部，不进行映射处理
     *
     * @return
     */
    public QueryResponseResult findByCommercialAndCommercialDetails(int page, int size, CommercialTenantNewRequest commercialTenantNewRequest) {
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(page, size);
        Agent agent = agentRepository.findByUserId(user1.getId());
        commercialTenantNewRequest.setAgentId(agent.getId());
        List<Map<String, Object>> list = commercialMapper.findByCommercialAndCommercialDetails(commercialTenantNewRequest);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        List list1 = pageInfo.getList();
        QueryResult queryResult = new QueryResult();
        queryResult.setTotal(total);
        queryResult.setList(list1);
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 根据商户id查询全部
     *
     * @param id
     * @return
     */
    private CommercialTenantNewExt getCommercialTenantNewExt(String id) {
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        CommercialTenant commercialTenant = optional.get();
        CommercialTenantDetails commercialTenantDetails = commercialTenantDetailsRepository.findByCommercialTenantId(commercialTenant.getId());
        if(commercialTenantDetails == null){
            commercialTenantDetails = new CommercialTenantDetails();
        }
        CommercialTenantNewExt commercialTenantNewExt = new CommercialTenantNewExt();
        commercialTenantNewExt.setCommercialTenant(commercialTenant);
        commercialTenantNewExt.setCommercialTenantDetails(commercialTenantDetails);
        return commercialTenantNewExt;
    }

    /**
     * 根据用户id查询代理商
     *
     * @param userId
     * @return
     */
    private Agent getAgentByUserId(String userId) {
        Agent byUserId = agentRepository.findByUserId(userId);
        return byUserId;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    private CommercialTenant getCommercialTenantById(String id) {
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 根据id查找用户表
     *
     * @param id
     * @return
     */
    private User getUserById(String id) {
        Optional<User> optional = userRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 查询所有商户名字
     * 判断当前登录账号，1.管理员是全部 2.代理商，查看其下的商户   3.商户，返回自己的
     * @return
     */
    public QueryResponseResult selectAllName() {
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        List<CommercialTenant> all = null;
        if(user1.getType()==0){
            //管理员
            all = commercialRepository.findAll();
        }
        if(user1.getType() == 1){
            //代理商
            Agent agent = agentRepository.findByUserId(user1.getId());
            all = commercialRepository.findByAgentIdAndIsDelete(agent.getId(),1);
        }
        if(user1.getType() == 2){
            //商户
            CommercialTenant commercialTenant = commercialRepository.findByUserId(user1.getId());
            all = new ArrayList<>();
            all.add(commercialTenant);
        }
        QueryResult queryResult = new QueryResult();
        queryResult.setTotal(all.size());
        queryResult.setList(all);
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);

    }

    /**
     * 查询图片Map格式
     *
     * @param id
     * @return
     */
    public ObjectResult findImgById(String id) {
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if (optional.isPresent()) {
            CommercialTenant commercialTenant = optional.get();
            Map map = JSONObject.parseObject(commercialTenant.getImageList(), Map.class);
            return new ObjectResult(CommonCode.SUCCESS, map);
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 通道申请
     *
     * @param
     * @return
     */
    public ResponseResult Channel(Channel channel) {
        if (channel != null) {
            channel.setStatus(1);//待审核
            String commercialId = channel.getCommercialId();
            int type = channel.getType();
            Channel channel1 = channelRepository.findByTypeAndCommercialId(type, commercialId);
            if (type == 1) {//微信
                if (channel1 != null) {
                    channel1.setAdminEmail(channel.getAdminEmail());
                    channel1.setAdminName(channel.getAdminName());
                    channel1.setAdminPhone(channel.getAdminPhone());
                    channel1.setAliPayNumber(channel.getAliPayNumber());
                    channel1.setBusinessNumber(channel.getBusinessNumber());
                    channel1.setCommercialId(channel.getCommercialId());
                    channel1.setCompanyName(channel.getCompanyName());
                    channel1.setImageUrl1(channel.getImageUrl1());
                    channel1.setImageUrl2(channel.getImageUrl2());
                    channel1.setImageUrl3(channel.getImageUrl3());
                    channel1.setRate(channel.getRate());
                    channel1.setNumber(channel.getNumber());
                    channelRepository.save(channel);
                }
            }
            if (type == 2) {//支付宝
                if (channel1 != null) {
                    channel1.setAdminEmail(channel.getAdminEmail());
                    channel1.setAdminName(channel.getAdminName());
                    channel1.setAdminPhone(channel.getAdminPhone());
                    channel1.setAliPayNumber(channel.getAliPayNumber());
                    channel1.setBusinessNumber(channel.getBusinessNumber());
                    channel1.setCommercialId(channel.getCommercialId());
                    channel1.setCompanyName(channel.getCompanyName());
                    channel1.setImageUrl1(channel.getImageUrl1());
                    channel1.setImageUrl2(channel.getImageUrl2());
                    channel1.setImageUrl3(channel.getImageUrl3());
                    channel1.setRate(channel.getRate());
                    channel1.setNumber(channel.getNumber());
                    channelRepository.save(channel);
                }
            }
            if (type == 3) {//建联
                if (channel1 != null) {
                    channel1.setAdminEmail(channel.getAdminEmail());
                    channel1.setAdminName(channel.getAdminName());
                    channel1.setAdminPhone(channel.getAdminPhone());
                    channel1.setAliPayNumber(channel.getAliPayNumber());
                    channel1.setBusinessNumber(channel.getBusinessNumber());
                    channel1.setCommercialId(channel.getCommercialId());
                    channel1.setCompanyName(channel.getCompanyName());
                    channel1.setImageUrl1(channel.getImageUrl1());
                    channel1.setImageUrl2(channel.getImageUrl2());
                    channel1.setImageUrl3(channel.getImageUrl3());
                    channel1.setRate(channel.getRate());
                    channel1.setNumber(channel.getNumber());
                    channelRepository.save(channel);
                }
            }
            Channel save = channelRepository.save(channel);
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new ResponseResult(null);
        }

    }

    //通道回显
    public QueryResponseResult EditChannel( String commercialId) {
        List<Channel> channel1 = channelRepository.findByCommercialId(commercialId);
        QueryResult queryResult=new QueryResult();
        queryResult.setTotal(channel1.size());
        queryResult.setList(channel1);
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 根据代理商id查询商户
     * @param id
     * @return
     */
    public ObjectResult findByAgentId(String id){
        List<CommercialTenant> list = commercialRepository.findByAgentId(id);
        return new ObjectResult(CommonCode.SUCCESS,list);
    }

    /**
     * 商户数据统计
     * @return
     */
    public ObjectResult findCommercialCount(){
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user1.getId());
        int count = 0;
        //查询全部商户
        if("1".equals(agent.getHierarchy())){
            count = commercialRepository.countByIsDelete(1);
        }
        //查询下面代理商的商户和自己的商户
        if("1-2".equals(agent.getHierarchy())){
            //查询出下面的代理商
            List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
            for (Agent agent1 : agentList) {
                count = count + commercialRepository.countByAgentIdAndIsDelete(agent1.getId(), 1);
            }

        }
        //查询自己的商户
        if("1-2-3".equals(agent.getHierarchy())){
            count = commercialRepository.countByAgentIdAndIsDelete(agent.getId(),1);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        return new ObjectResult(CommonCode.SUCCESS,map);
    }


    /**
     * 商户数据统计
     * @return
     */
    public ObjectResult findCommercialCountByTime(){
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user1.getId());
        int count = 0;
        //查询全部商户
        if("1".equals(agent.getHierarchy())){
            count = commercialRepository.countByIsDelete(1);
        }
        //查询下面代理商的商户和自己的商户
        if("1-2".equals(agent.getHierarchy())){
            //查询出下面的代理商
            List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
            for (Agent agent1 : agentList) {
                count = count + commercialRepository.countByAgentIdAndIsDelete(agent1.getId(), 1);
            }

        }
        //查询自己的商户
        if("1-2-3".equals(agent.getHierarchy())){
            count = commercialRepository.countByAgentIdAndIsDelete(agent.getId(),1);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        return new ObjectResult(CommonCode.SUCCESS,map);
    }


    public ResponseResult deleteListById(List<String> ids){
        for (String id : ids) {
            CommercialTenant one = this.getById(id);
            one.setIsDelete(0);
            commercialRepository.save(one);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public CommercialTenant getById(String id){
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
}
